<?php

namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use app\admin\model\SystemApplication;
use app\admin\model\SystemAuth;
use app\common\controller\AdminController;
use think\captcha\facade\Captcha;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use app\Request;
use think\facade\Session;
use think\Response;

class Auth extends AdminController
{

    protected bool $ignoreAuth = true;

    public function initialize(): void
    {
        parent::initialize();
        $action = $this->request->action();
        $data = $this->request->get();

        if (!empty($this->adminUid) && !in_array($action, ['out'])) {
            $auth_id = $this->checkData($data);
            $userInfo =  SystemAdmin::where('FIND_IN_SET(?, auth_ids)', [$auth_id])->where(['status'=>1,'id'=>$this->adminUid])->find();
            if (!empty($userInfo))
            {
                $adminModuleName = config('admin.alias_name');
                $this->success('已登录，无需再次登录', [], __url("@{$adminModuleName}"));
            }
        }
    }

    /**
     * 用户登录
     * @param Request $request
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index(Request $request): string
    {
        $data = $this->request->get();
        $token = $data['token'];
        $scope = $data['scope'];

        $auth_id = $this->checkData($data);
        $authKey = $this->generateRandomMixedCaseString(5);
        session('easy_key_'.$auth_id, $authKey);
        $users =  SystemAdmin::where('FIND_IN_SET(?, auth_ids)', [$auth_id])->where(['status'=>1])->select();
        $this->assign('users', $users);
        $this->assign('scope', $scope);
        $this->assign('token', $token);
        $this->assign('auth_id', $auth_id);
        $this->assign('scopeKey', $authKey);
        if (empty($users))
        {
            $this->errorMsg('没有匹配的用户');
        }
        return $this->fetch();
    }
    public function authuser (Request $request)
    {
        $data = $this->request->get();
        if (!isset($data['dataKey']) || empty($data['dataKey']))
        {
            $this->errorMsg('参数错误!缺少参数:data key');
        }
        if (!isset($data['scope_key']) || empty($data['scope_key']))
        {
            $this->errorMsg('参数错误!!缺少参数:scope key');
        }

        $sessionArray = explode('-', $data['dataKey']);
        if (session($sessionArray[0]) === null || session($sessionArray[0]) !== $data['scope_key'])
        {
            $this->errorMsg('scope key验证错误');
        }

        $auth_id = $this->checkData($data);

        $users =  SystemAdmin::where('FIND_IN_SET(?, auth_ids)', [$auth_id])->where(['status'=>1,'id'=>$sessionArray[1]])->find();
        if (empty($users))
        {
            $this->errorMsg('验证登录错误');
        }
        $users->login_num += 1;
        $users->save();
        $admin = $users->toArray();
        $admin['expire_time'] = time() + 7200;
        session('admin', $admin);
        $this->success('授权成功!','','/index');
    }

    protected function checkData ($data)
    {
        $application = SystemApplication::where(['auth_token' => $data['token'],'status' => 1])->find();
        if (empty($application))
        {
            $this->errorMsg('token不存在');
        }
        $auth_ids = explode(',', $application->auth_ids ?: '');
        if (empty($auth_ids))
        {
            $this->errorMsg('应用不存在');
        }
        $auth = SystemAuth::where(['identify' => $data['scope']])->find();
        if (empty($auth))
        {
            $this->errorMsg('scope不存在');
        }
        if (!in_array($auth->id, $auth_ids))
        {
            $this->errorMsg('scope不匹配');
        }
        return $auth->id;
    }
    protected function generateRandomMixedCaseString($length = 5) {
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            do {
                $randomLetter = chr(rand(65, 122));
            } while (!ctype_alpha($randomLetter));
            $randomString .= $randomLetter;
        }
        $numberStr = rand(10000, 99999);
        return '_'.$randomString.$numberStr;
    }
}
